package main

import (
	"context"
	"fmt"
	"gin/app/config"
	"gin/app/http/global"
	"gin/app/http/routers"
	"gin/app/http/util/es"
	"gin/app/http/util/mysql"
	"gin/app/http/util/redis"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"sync"
	"time"
)

func main() {

	defer shutdown()

	r := gin.Default()
	if err := config.InitConfig(); err != nil {
		fmt.Println(err)
	}

	fmt.Println("########初始化开始###########")

	//1.初始化mysql
	if err := mysql.InitMysql(); err != nil {
		fmt.Println(err)
	}
	//2.初始化redis
	if err := redis.InitRedis(&gin.Context{}); err != nil {
		fmt.Println(err)
	}

	//3.初始化es
	if err := es.InitEs(); err != nil {
		fmt.Println(err)
	}

	fmt.Println("########初始化结束###########")

	//2.初始化路由
	routers.InitRouters(r)
	//test()
	// 3.监听端口，默认在8080
	// Run("里面不指定端口号默认为8080")

	r.Run(viper.GetString("server.addr"))
}

func shutdown() {
	//关闭mysql连接
	//关闭redis连接
	//关闭es连接
}

func test() {
	var wg sync.WaitGroup
	//var mu sync.Mutex
	numRequests := 20000

	for i := 0; i < numRequests; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			//time.Sleep(time.Second * 1)
			//mu.Lock()
			//defer mu.Unlock()

			stats := global.Rdb.PoolStats()
			fmt.Printf("活跃连接数: %d, 空闲连接数: %d\n", stats.Hits, stats.IdleConns)
			// 设置日志输出，将连接过程的日志打印到控制台
			global.Rdb.Set(context.Background(), "aaaa", "2222", time.Hour).Result()
		}()
	}
	wg.Wait()
	//global.Rdb.Close()

}
